package syf.Josepfu;

public class josepfu {
    public static void main(String[] args) {
        circleSingleList cs=new circleSingleList();
        cs.addBoys(50);
        cs.showBoy();
        cs.out(1,2,5);
    }
}
//环形单向链表
class circleSingleList{
    //创建一个first
    private Boy first=null;

    public  void addBoys(int nums){
        Boy curr_boy=null;
        if (nums<1) {
            System.out.println("输入个数必须大于1");
            return;
        }
        else{
            for (int i=1;i<=nums;i++){
                Boy boy=new Boy(i);
                if (i==1){//构建第一个环
                    first=boy;
                    first.setNext(first);
                    curr_boy=first;
                }else{//将其他环构建起来
                    curr_boy.setNext(boy);
                    boy.setNext(first);
                    curr_boy=boy;
                }
            }
        }
    }
    public void showBoy(){
        Boy curr_boy=null;
        curr_boy=first;
        if (null!=first)
        while (true){
            if (curr_boy.getNext()==first) {
                System.out.println("第" + curr_boy.getNo() + "个小孩");
                break;
            }
            else {
                System.out.println("第" + curr_boy.getNo() + "个小孩");
                curr_boy = curr_boy.getNext();
            }
        }
    }
    /**
     * @param startno 开始报数的号
     * @param num 每次报几个
     * @param nums 最初小孩的数量
     */
    //出圈
    public void out(int startno,int num,int nums){
        Boy helper=first;
        if (first==null|num<1|nums<1) {
            System.out.println("有误");
            return;
        }
        //将helper移动到first的后面一个
        while (true){
            if (helper.getNext()==first)
                break;
            helper=helper.getNext();
        }
        //将first和helper移动到报数的号位置
        for (int i=0;i<startno-1;i++){
            helper=helper.getNext();
            first=first.getNext();
        }
        //开始报数，出圈
        while (true){
            if (first==helper) {//只剩一个了
                System.out.println("剩余孩子的编号为"+first.getNo());
                break;
            }
            else{
                //出圈
                for (int i=0;i<num-1;i++){
                    helper=helper.getNext();
                    first=first.getNext();
                }
                System.out.println("出圈孩子的编号为"+first.getNo());
                first=first.getNext();
                helper.setNext(first);
                first=helper.getNext();
            }
        }
    }
}
//BOY类表示节点
class Boy{
    private int no;
    private Boy next;
    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
    public Boy getNext() {
        return next;
    }
    public void setNext(Boy next) {
        this.next = next;
    }
    public Boy(int no){this.no=no;}
}
